package com.qf.fmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.product.entity.Product;
import com.qf.fmall.product.entity.ProductImg;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductImgMapper;
import com.qf.fmall.product.mapper.ProductMapper;
import com.qf.fmall.product.mapper.ProductSkuMapper;
import com.qf.fmall.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall.product.vo.ProductDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wbw
 * @since 2023-11-29
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductImgMapper productImgMapper;
    @Override
    public List<Product> listRecommends() {
        //1.查商品信息
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        wrapper.last("limit 3");
        List<Product> products = productMapper.selectList(wrapper);
        //2.查商品的图片信息
        addPic(products);

        return products;
    }
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Override
    public ProductDetailVo detailInfo(Integer id) {
        //1. 根据id查询商品基本信息
        Product product = productMapper.selectById(id);
        //2. 根据id查询商品的sku信息
        QueryWrapper<ProductSku> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id",id);
        List<ProductSku> productSkus = productSkuMapper.selectList(wrapper);

        //3. 根据id查询商品的图片信息
        List<ProductImg> productImgs = productImgMapper.selectList(new QueryWrapper<ProductImg>().eq("product_id", id));

        ProductDetailVo productDetailVo = new ProductDetailVo();
        productDetailVo.setProduct(product);
        productDetailVo.setProductSkus(productSkus);
        productDetailVo.setProductImgs(productImgs);

        return productDetailVo;
    }

    private void addPic(List<Product> products) {
        for (Product product : products) {
            QueryWrapper<ProductImg> wrapper = new QueryWrapper<>();
            wrapper.eq("product_id",product.getProductId());
            List<ProductImg> productImgs = productImgMapper.selectList(wrapper);
            product.setImgs(productImgs);
        }
    }
}
